#!/bin/bash
#默认变量值
TOMCAT_HOME="/usr/local/tomcat"
TOMCAT_PORT=8080
PROJECT="$1"
WEB_DIR="/data/wwwroot/default"
#参数检验./deploy.sh <projectname> [tomcat port] [tomcat home dir]
if [ $# -lt 1 ]; then
  echo "you must use like this : ./deploy.sh <projectname> [tomcat port] [tomcat home dir] [webapps dir]"  
  exit
fi
if [ -n "$2" ]; then
   TOMCAT_PORT=$2
fi
if [ -n "$3" ]; then
   TOMCAT_HOME="$3"
fi
if [ -n "$4" ]; then
   WEB_DIR="$4"
fi

#根据端口查找tomcatpid,可能有多个,循环中判断
tomcat_pid=`netstat -anp | grep $TOMCAT_PORT | awk '{printf $7}' | cut -d "/" -f 1`
echo "current :" $tomcat_pid
while [ -n "$tomcat_pid" ]
do
 sleep 5
 #进一步筛选
 #tomcat_pid=`ps -ef | grep $tomcat_pid |grep $TOMCAT_HOME | grep -v 'grep\|tail\|more\|bash\|less'| awk '{print $2}'`
 tomcat_pid=`ps -ef | grep $TOMCAT_HOME | grep -v 'grep\|tail\|more\|bash\|less'| awk '{print $2}'`
 echo "scan tomcat pid :" $tomcat_pid
 if [ -n "$tomcat_pid" ]; then
   echo "kill tomcat :" $tomcat_pid
   kill -9 $tomcat_pid
 fi
done

#备份路径
BAK_DIR=$HOME/war/bak/$PROJECT/`date +%Y%m%d`
mkdir -p "$BAK_DIR"

if [ -d "$WEB_DIR"/$PROJECT.war ]; then
   cp "$WEB_DIR"/$PROJECT.war "$BAK_DIR"/"$PROJECT"_`date +%H%M%S`.war
fi

#publish project
echo "scan no tomcat pid,$PROJECT publishing"
rm -rf "$WEB_DIR"/*
cp $HOME/war/$PROJECT.war "$WEB_DIR"/$PROJECT.war
cd "$WEB_DIR"
/usr/java/jdk1.8.0_192/bin/jar -xvf $PROJECT.war
sleep 3
chown -R www:www "$WEB_DIR"

#remove tmp
rm -rf $HOME/war/$PROJECT.war
#start tomcat
su - www -c "$TOMCAT_HOME"/bin/startup.sh
echo "tomcat is starting,please try to access $PROJECT conslone url"
